class Square extends React.Component {
  render() {
    let className = ['square'];
    if(this.props.isActive) {
      className.push('active');
    }
    if(this.props.isWinPos) {
      className.push('win');
    }
    return (
      <button className={className.join(' ')} onClick={ this.props.onClick }>
        {this.props.value}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square value={ this.props.squares[i] }
              isActive={this.props.step === i}
              isWinPos={this.props.winPos.indexOf(i)>-1 }
              onClick={ () => this.props.handleClick(i) }
            />;
  }
  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  constructor() {
    super();
    this.state = {
      history: [{
        squares: Array(9).fill(null),
        step:null
      }],
      xIsNext: true,
      currentIndex: 0
    };
  }
  handleClick(i){
    let history = this.state.history.slice(0, this.state.currentIndex + 1);
    const current = history[this.state.currentIndex];    
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }    
    squares[i] = this.state.xIsNext ? 'X' : 'O'; 
    this.setState({
      history: history.concat([{
        squares: squares,
        step: i
      }]),
      xIsNext: !this.state.xIsNext,
      currentIndex: ++this.state.currentIndex,
    });
  }  
  jumpTo(index) {
    this.setState({
      currentIndex: index,
      xIsNext: (index % 2) ? false : true,
    });
  }
  render() {
    const history = this.state.history;
    const currentIndex = this.state.currentIndex;
    const current = history[this.state.currentIndex];
    const winner = calculateWinner(current.squares) && calculateWinner(current.squares).winer; 
    const winPos = calculateWinner(current.squares) && calculateWinner(current.squares).winPos || []; 
    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    } 
    return (
      <div className="game">
        <div className="game-board">
          <Board squares={current.squares} 
                 step={current.step} 
                 winPos={winPos}
                 handleClick={ (i)=> this.handleClick(i) }/>
        </div>
        <div className="game-info">
          <div>{ status }</div>
          <ol>
          { 
            history.map( (item, index) => {
              let next = (index % 2) ? 'X' : 'O';
              let msg = index === 0 ?
                 '游戏开始':
                 '第'+ index + '步, ' + next +'位置(' + transformToTwo(item.step) +')';
              return (
              <li key={index} className={ index === currentIndex ? 'active': ''}>
                <a href="#" onClick={ () => this.jumpTo(index) }> {msg}</a>
              </li>)
            }) 
          }
          </ol>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return {
        winer: squares[a],
        winPos: [a, b, c]
      };
    }
  }
  return null;
}

function transformToTwo(index){
  return [ Math.floor(index/3), index % 3];
}